using MediatR;
using RBAC_Class.Domain;
using RBAC_Class.ErrorCode;
using RBAC_Class.Infrastructrue.Interfaces;
using RBAC_Class.Write.API.Application.Command.Users;
using System;
using NLog;

namespace RBAC_Class.Write.API.Application.CommandHandler.Users
{
    public class UpdateUserCommandHandler : IRequestHandler<UpdateUserCommand, APIResult<int>>
    {
        private readonly IBaseRepository<User> userRep;
        private readonly IBaseRepository<UserRole> userRoleRep;
        private readonly ILogger<UpdateUserCommandHandler> logger;

        public UpdateUserCommandHandler(IBaseRepository<User> userRep, IBaseRepository<UserRole> userRoleRep, ILogger<UpdateUserCommandHandler> logger)
        {
            this.userRep = userRep;
            this.userRoleRep = userRoleRep;
            this.logger = logger;
        }

        public Task<APIResult<int>> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var user = userRep.GetAll().FirstOrDefault(x => x.UserID == request.UserID && x.IsDelete == false);
                if (user == null)
                {
                    return Task.FromResult(new APIResult<int> { Code = ResultCode.Fail, Message = "用户不存在" });
                }
                user.UserName = request.UserName;
                user.Password = request.Password; // 建议加密
                user.Status = 1;
                userRep.Update(user);

                // 软删除原有角色
                var userRoles = userRoleRep.GetAll().Where(x => x.UserID == request.UserID && x.IsDelete == false).ToList();
                foreach (var ur in userRoles)
                {
                    ur.IsDelete = true;
                    userRoleRep.Update(ur);
                }
                // 添加新角色
                foreach (var roleId in request.RoleIDs)
                {
                    userRoleRep.Add(new UserRole
                    {
                        UserID = request.UserID,
                        RoleID = roleId,
                        CreateTime = DateTime.Now,
                        IsDelete = false
                    });
                }
                return Task.FromResult(new APIResult<int> { Code = ResultCode.Success, Message = "修改成功", Data = user.UserID });
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "更新用户失败 - 用户ID: {UserID}, 用户名: {UserName}, 角色IDs: {RoleIDs}", 
                    request.UserID, request.UserName, string.Join(",", request.RoleIDs));
                throw;
            }
        }
    }
} 